import axios from 'axios'
import store from 'store/index'
import { Toast } from 'vant';

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 10000 // request timeout
});

// request interceptor
service.interceptors.request.use(
    config => {
        let token = store.state.token;
        token && (config.headers.Authorization = token);
        return config
    },
    error => {
        return Promise.error(error)
    }
);

// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */
    response => {
        console.log(response);
        if (response.status === 200 && (response.data.code === 200 || response.data.errcode === 0 || response.data.code === 0)) {
            return Promise.resolve(response.data)
        } else {
            // console.log(response.data);
            let Msg = response.data.msg || '网络故障!';
            if (response.data.msg === 'TOKEN_INVALID') {
                Msg = '授权失败!';
                store.commit('updateToken', undefined);
            }

            Toast(Msg);
            return Promise.reject(response)
        }
    },
    error => {
        console.log('--');
        console.log(error);
        // Indicator.close()
        let responseCode = -1;
        if (error.response) {
            responseCode = error.response.status;
        }
        switch (responseCode) {
            // 401：未登录
            case 401:
                break;
            // 404请求不存在
            case 404:
                Toast('请求不存在!');
                break;
            case 500:
                Toast('网络故障!');
                break;
            case -1:
                Toast('网络故障!');
                break;
            default:
                Toast(error.response.data.message || '网络故障!');
        }

        return Promise.reject(error.response)
    }
);

export function httpUpload(url, file) {
    let param = new FormData();
    param.append('file', file);
    return service({
        url: url,
        method: 'post',
        data: param,
        headers: { 'Content-Type': 'multipart/form-data' }
    })
}

export function httpPost(url, params) {
    return service({
        url: url,
        method: 'post',
        data: params
    })
}

export function httpGet(url, params) {
    return service({
        url: url,
        method: 'get',
        params: params
    })
}
